import { defineStore } from 'pinia';
import type { User } from '@/http/User';

export interface UserState {
  userId: number | null;
  userInfo: User | null;
  isLoggedIn: boolean;
  token: string | null;
  lastOperation: string;
  timestamp: string;
}

export const useUserIdStore = defineStore('userId', {
  state: (): UserState => ({
    userId: null,
    userInfo: null,
    isLoggedIn: false,
    token: null,
    lastOperation: '',
    timestamp: ''
  }),
  
  actions: {
    // 设置用户ID
    setUserId(id: number | null, operation = '') {
      this.userId = id;
      this.lastOperation = operation;
      this.timestamp = new Date().toLocaleTimeString();
      this.isLoggedIn = id !== null;
      
      // 持久化到本地存储
      if (id !== null) {
        localStorage.setItem('userId', id.toString());
      } else {
        localStorage.removeItem('userId');
      }
    },
    
    // 设置用户完整信息
    setUserInfo(user: User, operation = '') {
      this.userInfo = user;
      this.userId = user.id;
      this.isLoggedIn = true;
      this.lastOperation = operation;
      this.timestamp = new Date().toLocaleTimeString();
      
      // 持久化到本地存储
      if (user.id !== null) {
        localStorage.setItem('userId', user.id.toString());
        localStorage.setItem('userInfo', JSON.stringify(user));
      }
    },
    
    // 设置token
    setToken(token: string | null) {
      this.token = token;
      if (token) {
        localStorage.setItem('token', token);
      } else {
        localStorage.removeItem('token');
      }
    },
    
    // 登录
    login(user: User, token?: string, operation = 'Login') {
      this.setUserInfo(user, operation);
      if (token) {
        this.setToken(token);
      }
    },
    
    // 登出
    logout() {
      this.userId = null;
      this.userInfo = null;
      this.isLoggedIn = false;
      this.token = null;
      this.lastOperation = 'Logout';
      this.timestamp = new Date().toLocaleTimeString();
      
      // 清除本地存储
      localStorage.removeItem('userId');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('token');
    },
    
    // 重置用户ID
    resetUserId() {
      this.userId = -1;
      this.lastOperation = 'Reset';
      this.timestamp = new Date().toLocaleTimeString();
    },
    
    // 从本地存储恢复状态
    restoreFromStorage() {
      try {
        const storedUserId = localStorage.getItem('userId');
        const storedUserInfo = localStorage.getItem('userInfo');
        const storedToken = localStorage.getItem('token');
        
        console.log('🔄 尝试从本地存储恢复用户状态...', {
          hasUserId: !!storedUserId,
          hasUserInfo: !!storedUserInfo,
          hasToken: !!storedToken
        });
        
        let restored = false;
        
        if (storedUserId) {
          const parsedUserId = parseInt(storedUserId);
          if (!isNaN(parsedUserId) && parsedUserId > 0) {
            this.userId = parsedUserId;
            this.isLoggedIn = true;
            restored = true;
            console.log('✅ 用户ID已恢复:', parsedUserId);
          }
        }
        
        if (storedUserInfo) {
          try {
            const parsedUserInfo = JSON.parse(storedUserInfo);
            if (parsedUserInfo && parsedUserInfo.id) {
              this.userInfo = parsedUserInfo;
              // 确保用户ID一致
              if (!this.userId) {
                this.userId = parsedUserInfo.id;
                this.isLoggedIn = true;
              }
              restored = true;
              console.log('✅ 用户信息已恢复:', parsedUserInfo.account);
            }
          } catch (error) {
            console.error('❌ 解析用户信息失败:', error);
            // 清除损坏的数据
            localStorage.removeItem('userInfo');
          }
        }
        
        if (storedToken) {
          this.token = storedToken;
          console.log('✅ Token已恢复');
        }
        
        if (restored) {
          this.lastOperation = 'RestoreFromStorage';
          this.timestamp = new Date().toLocaleTimeString();
          console.log('✅ 用户状态恢复成功:', {
            userId: this.userId,
            isLoggedIn: this.isLoggedIn,
            hasUserInfo: !!this.userInfo,
            hasToken: !!this.token
          });
        } else {
          console.log('⚠️ 没有找到有效的用户状态数据');
        }
        
        return restored;
      } catch (error) {
        console.error('❌ 恢复用户状态时发生错误:', error);
        // 发生错误时清除可能损坏的数据
        this.clearCorruptedData();
        return false;
      }
    },
    
    // 清除损坏的数据
    clearCorruptedData() {
      console.log('🧹 清除损坏的本地存储数据...');
      localStorage.removeItem('userId');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('token');
      this.logout();
    }
  },
  
  getters: {
    currentUserId: (state) => state.userId,
    currentUser: (state) => state.userInfo,
    isAuthenticated: (state) => state.isLoggedIn && state.userId !== null,
    operationDetails: (state) => 
      state.lastOperation ? `${state.lastOperation} at ${state.timestamp}` : 'No operation yet'
  }
});